package com.example.work8_1.Service;


import com.example.work8_1.DAO.ProductRepository;
import com.example.work8_1.Exception.ProductException;
import com.example.work8_1.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductService {
    @Autowired
    ProductRepository pr;


    //增
    public Product addProduct(Product p) throws ProductException
    {
        if(p.getId() != null && pr.findById(p.getId()).isPresent())
        {
            throw new ProductException("该商品已存在");
        }
        return pr.save(p);
    }

    //删
    public void deleteProduct(Integer id) throws ProductException
    {
        if(!pr.findById(id).isPresent())
        {
            throw new ProductException("该商品不存在");
        }
        pr.deleteById(id);
    }

    //改
    public void updateProduct(Integer id,Product p)throws ProductException
    {
        if(!pr.findById(id).isPresent())
        {
            throw new ProductException("该商品不存在");
        }
        pr.saveAndFlush(p);
    }

    //查
    public Product findProduct(Integer id)throws ProductException
    {
        if(!pr.findById(id).isPresent())
        {
            throw new ProductException("该商品不存在");
        }
        return pr.findById(id).get();
    }
}
